import { createRouter, createWebHashHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import LoginView from '../views/LoginView.vue'
import RegisterView from '../views/RegisterView.vue'
import CourseDetailView from '../views/CourseDetailView.vue'
import AddCategoryView from '../views/AddCategoryView.vue'
import AddCourseView from '../views/AddCourseView.vue'
import AddSubitemView from '../views/AddSubitemView.vue'
import AddTaskView from '../views/AddTaskView.vue'
import SimpleLoginTest from '../views/SimpleLoginTest.vue'
import LoginTest from '../views/LoginTest.vue'

// 路由配置
const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
    meta: {
      title: '首页 - 课程学习网站'
    }
  },
  {
    path: '/login',
    name: 'login',
    component: LoginView,
    meta: {
      title: '登录 - 课程学习网站'
    }
  },
  {
    path: '/register',
    name: 'register',
    component: RegisterView,
    meta: {
      title: '注册 - 课程学习网站'
    }
  },
  {
    path: '/course/:id',
    name: 'courseDetail',
    component: CourseDetailView,
    meta: {
      title: '课程详情 - 课程学习网站'
    }
  },
  {
    path: '/add-category',
    name: 'addCategory',
    component: AddCategoryView,
    meta: {
      title: '添加课程类别 - 课程学习网站',
      requiresAuth: true
    }
  },
  {
    path: '/add-course',
    name: 'addCourse',
    component: AddCourseView,
    meta: {
      title: '添加课程 - 课程学习网站',
      requiresAuth: true
    }
  },
  {
    path: '/add-subitem/:courseId',
    name: 'addSubitem',
    component: AddSubitemView,
    meta: {
      title: '添加课程任务项 - 课程学习网站',
      requiresAuth: true
    }
  },
  {    path: '/simple-login-test',    name: 'simpleLoginTest',    component: SimpleLoginTest,    meta: {      title: '简单登录测试 - 课程学习网站'    }  },
  {
    path: '/login-test',
    name: 'loginTest',
    component: LoginTest,
    meta: {
      title: '登录功能测试 - 课程学习网站'
    }
  },
  {
    path: '/add-task',
    name: 'addTask',
    component: AddTaskView,
    meta: {
      title: '添加课程任务项 - 课程学习网站',
      requiresAuth: true
    }
  }

]

// 创建路由实例
const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 全局路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = to.meta.title
  }
  
  // 检查是否需要登录
  if (to.meta.requiresAuth) {
    const token = localStorage.getItem('token')
    const userInfo = localStorage.getItem('userInfo')
    if (token && userInfo) {
      next()
    } else {
      next('/login')
    }
  } else {
    next()
  }
})

export default router